package ro.ase.catalog.security.action;

import com.opensymphony.xwork2.ActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.PasswordEncoder;
import ro.ase.catalog.beans.*;
import ro.ase.catalog.beans.dto.StudentDTO;
import ro.ase.catalog.beans.dto.TeacherDTO;
import ro.ase.catalog.security.dao.IRoleDAO;
import ro.ase.catalog.security.dao.ISchoolClassDAO;
import ro.ase.catalog.security.service.IStudentService;
import ro.ase.catalog.security.service.ITeacherDisciplineClassService;
import ro.ase.catalog.security.service.ITeacherService;
import ro.ase.catalog.security.service.IUserService;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Ioana
 * Date: 5/12/14
 * Time: 2:28 PM
 * To change this template use File | Settings | File Templates.
 */
public class AdminAction extends ActionSupport {

    @Autowired
    private IUserService userService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private ISchoolClassDAO schoolClassDAO;
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ITeacherDisciplineClassService teacherDisciplineClassService;
    @Autowired
    private IRoleDAO roleDAO;
    private Student student;
    private Teacher teacher;
    private User user;
    private String comboValue;
    private String teacherFunction;
    private String teacherMaster;
    private String disciplineName;
    private String className;
    private int totalCount;
    private String searchName;
    private String plainpasswordAgain;
    private int start;
    private TeacherDTO teacherDTO;
    private SchoolClass schoolClass;
    private Discipline discipline;
    private Teacher teacherDisc;
    private int limit;

    private StudentDTO studentDTO;
    /////////////////////////

    private int roleId;


    private int[] userIds;

    private boolean binded;

    private Map<String,Object> resultMap = new HashMap<String,Object>();


    private List<Setting> settings;

    private String username;
    private String key;
    private String password;
    private String repassword;
    @Autowired
    private PasswordEncoder passwordEncoder;
    private List<Discipline> disciplineList;
    private Map<String, Object>  adminMap=new HashMap<String, Object>();

    public String findStudents()
    {   List<StudentDTO> students;
        if(studentDTO==null)
            students=studentService.findByName(null, start, limit);
        else
            students= studentService.findByName(studentDTO.getLastName(), start, limit);
        adminMap.put("totalCount", totalCount);
        adminMap.put("success", true);
        adminMap.put("data", students);

        return SUCCESS;
    }

    public String updateStudent()
    {   SchoolClass schoolClassUpdate=null;
        boolean message=true;

        Student studentUpdate=studentService.getStudentById(studentDTO.getId());
        if(studentUpdate.getSchoolClass()!=null)
        {
            if(!studentDTO.getClassName().equals(studentUpdate.getSchoolClass().getName()))
            {
                schoolClassUpdate=schoolClassDAO.findByName(studentDTO.getClassName());
                if(schoolClassUpdate==null)
                {
                    message=false;


                }
                else
                {
                    studentUpdate.setSchoolClass(schoolClassUpdate);
                }


            }  }
        else
        {
            if(!studentDTO.getClassName().equals("-"))
            {
                schoolClassUpdate=schoolClassDAO.findByName(studentDTO.getClassName());
                if(schoolClassUpdate==null)
                {
                    message=false;

                }
                else
                {
                    studentUpdate.setSchoolClass(schoolClassUpdate);
                }


            }
        }
        studentUpdate.setLastName(studentDTO.getLastName());
        studentUpdate.setAddress(studentDTO.getAddress());
        studentUpdate.setPhone(studentDTO.getPhone());
        studentService.updateStudent(studentUpdate);
        // adminMap.put("info");
        adminMap.put("message",message );
        return SUCCESS;
    }
    public String findAllTeachers() {

        List<TeacherDTO> teachers = teacherService.findByName(searchName, start, limit);
        adminMap.put("totalCount", totalCount);
        adminMap.put("success", true);
        adminMap.put("data", teachers);

        return SUCCESS;

    }
    public String updateTeacher() {
        Teacher teacherUpdate=teacherService.getTeacherById(teacherDTO.getId()) ;
        teacherUpdate.setLastName(teacherDTO.getLastName());
        teacherService.updateTeacher(teacherUpdate);
        return SUCCESS;

    }
    public String deleteTeacher() {
        Teacher teacherUpdate=teacherService.getTeacherById(teacherDTO.getId()) ;
        teacherService.deleteTeacherTransactional(teacherUpdate,teacherUpdate.getUser());
        adminMap.put("message", getText("save.success"));
        adminMap.put("success", true);
        return SUCCESS;

    }
    public String saveTeacher(){
         if(teacherService.findByUserName(user.getLoginname())==null)    {
        String cryptpassword=passwordEncoder.encodePassword(user.getPlainpassword(), null);
        user.setCryptpassword(cryptpassword);
        user.setRoles(new HashSet<Role>() {{
            add(roleDAO.findByRolename("ROLE_TEACHER"));
        }});
        teacher.setUser(user);
        if(teacherMaster.equals("NU"))
            teacher.setClassMaster(null);
        else
            teacher.setClassMaster(schoolClassDAO.findByName(teacherMaster));
        teacher.setFunction(teacherFunction);
        try{
            if(teacherService.saveTransactionalTeacher(user, teacher))
            {
                adminMap.put("message", getText("save.success"));
                adminMap.put("success", true);
            }
            else
            {
                adminMap.put("message", "Salvare esuata");
                adminMap.put("success", false);
            }
        }catch (Exception ex){
            adminMap.put("message", "Salvare esuata");
            adminMap.put("success", false);
        }
         }
        else{
             adminMap.put("message", "Utilizator deja existent");
             adminMap.put("success", false);
         }
        return SUCCESS;
    }

    public String saveStudent(){
      //  if(studentService.findByUs(user.getLoginname())==null)    {
        String cryptpassword=passwordEncoder.encodePassword(user.getPlainpassword(), null);
        user.setCryptpassword(cryptpassword);
        user.setRoles(new HashSet<Role>() {{
            add(roleDAO.findByRolename("ROLE_STUDENT"));
        }});
        student.setUser(user);
        student.setSchoolClass(schoolClassDAO.findByName(comboValue));
        try{
            if(studentService.saveTransactionalStudent(user,student)) {
                adminMap.put("message", getText("save.success"));
                adminMap.put("success", true);
            }
            else {
                adminMap.put("message", "Salvare esuata");
                adminMap.put("success", false);

            }
        }catch (Exception ex){
            adminMap.put("message", "Salvare esuata");
            adminMap.put("success", false);
        }
        return SUCCESS;
    }

    public String associateDiscipline(){

        setTeacherDisc(teacherService.getByLastNameFirstName(teacher.getLastName(), teacher.getFirstName()));
        setDiscipline(teacherDisciplineClassService.findDisciplineByName(disciplineName));
        setSchoolClass(schoolClassDAO.findByName(className));
        TeacherDisciplineClass disciplineClass=new TeacherDisciplineClass();
        disciplineClass.setaSchoolClass(schoolClass);
        disciplineClass.setDiscipline(discipline);
        disciplineClass.setTeacher(teacherDisc);
        if(teacherDisciplineClassService.checkAssociation(disciplineName, className)==null) {
            teacherDisciplineClassService.saveTeacherDisciplineClass(disciplineClass);
            adminMap.put("message", "success");
            adminMap.put("success", true);
            adminMap.put("association",true );
        }
        else{
            adminMap.put("message", "success");
            adminMap.put("success", true);
            adminMap.put("association", false);
            adminMap.put("discipline", discipline.getName() )    ;
            adminMap.put("clasa", schoolClass.getName()) ;
            adminMap.put("teacherLastName", teacher.getLastName());
            adminMap.put("teacherFirstName", teacher.getFirstName());
        }

        return  SUCCESS;
    }

    public String saveAssociation(){
        SchoolClass schoolClass1=schoolClassDAO.findByName(schoolClass.getName());
        Discipline discipline1=teacherDisciplineClassService.findDisciplineByName(discipline.getName());
        Teacher teacher1=teacherService.getByLastNameFirstName(teacher.getLastName(), teacher.getFirstName());
        TeacherDisciplineClass disciplineClass=new TeacherDisciplineClass();
        disciplineClass.setaSchoolClass(schoolClass1);
        disciplineClass.setDiscipline(discipline1);
        disciplineClass.setTeacher(teacher1);
        teacherDisciplineClassService.saveTeacherDisciplineClass(disciplineClass);
        return SUCCESS;
    }

    public String loadDiscipline(){
        setDisciplineList(teacherDisciplineClassService.getAllDisciplines());
        adminMap.put("disciplineList", getDisciplineList());
        return SUCCESS;
    }
    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public IStudentService getStudentService() {
        return studentService;
    }

    public void setStudentService(IStudentService studentService) {
        this.studentService = studentService;
    }

    public Map<String, Object> getAdminMap() {
        return adminMap;
    }

    public void setAdminMap(Map<String, Object> adminMap) {
        this.adminMap = adminMap;
    }

    public ISchoolClassDAO getSchoolClassDAO() {
        return schoolClassDAO;
    }

    public void setSchoolClassDAO(ISchoolClassDAO schoolClassDAO) {
        this.schoolClassDAO = schoolClassDAO;
    }

    public String getComboValue() {
        return comboValue;
    }

    public TeacherDTO getTeacherDTO() {
        return teacherDTO;
    }

    public void setTeacherDTO(TeacherDTO teacherDTO) {
        this.teacherDTO = teacherDTO;
    }

    public void setComboValue(String comboValue) {
        this.comboValue = comboValue;
    }

    public String getPlainpasswordAgain() {
        return plainpasswordAgain;
    }

    public void setPlainpasswordAgain(String plainpasswordAgain) {
        this.plainpasswordAgain = plainpasswordAgain;
    }

    public String getTeacherFunction() {
        return teacherFunction;
    }

    public void setTeacherFunction(String teacherFunction) {
        this.teacherFunction = teacherFunction;
    }

    public String getTeacherMaster() {
        return teacherMaster;
    }

    public void setTeacherMaster(String teacherMaster) {
        this.teacherMaster = teacherMaster;
    }

    public ITeacherService getTeacherService() {
        return teacherService;
    }

    public void setTeacherService(ITeacherService teacherService) {
        this.teacherService = teacherService;
    }

    public PasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }

    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    public ITeacherDisciplineClassService getTeacherDisciplineClassService() {
        return teacherDisciplineClassService;
    }

    public void setTeacherDisciplineClassService(ITeacherDisciplineClassService teacherDisciplineClassService) {
        this.teacherDisciplineClassService = teacherDisciplineClassService;
    }

    public String getDisciplineName() {
        return disciplineName;
    }

    public void setDisciplineName(String disciplineName) {
        this.disciplineName = disciplineName;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public String getSearchName() {
        return searchName;
    }

    public void setSearchName(String searchName) {
        this.searchName = searchName;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public int getRoleId() {

        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public int[] getUserIds() {
        return userIds;
    }

    public void setUserIds(int[] userIds) {
        this.userIds = userIds;
    }

    public boolean isBinded() {
        return binded;
    }

    public void setBinded(boolean binded) {
        this.binded = binded;
    }

    public Map<String, Object> getResultMap() {
        return resultMap;
    }

    public void setResultMap(Map<String, Object> resultMap) {
        this.resultMap = resultMap;
    }

    public List<Setting> getSettings() {
        return settings;
    }

    public void setSettings(List<Setting> settings) {
        this.settings = settings;
    }

    public String getUsername() {
        return username;
    }
    public List<Discipline> getDisciplineList() {
        return disciplineList;
    }

    public void setDisciplineList(List<Discipline> disciplineList) {
        this.disciplineList = disciplineList;
    }

    public Teacher getTeacherDisc() {
        return teacherDisc;
    }

    public void setTeacherDisc(Teacher teacherDisc) {
        this.teacherDisc = teacherDisc;
    }

    public Discipline getDiscipline() {
        return discipline;
    }

    public void setDiscipline(Discipline discipline) {
        this.discipline = discipline;
    }

    public SchoolClass getSchoolClass() {
        return schoolClass;
    }

    public void setSchoolClass(SchoolClass schoolClass) {
        this.schoolClass = schoolClass;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRepassword() {
        return repassword;
    }

    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }

    public IRoleDAO getRoleDAO() {
        return roleDAO;
    }

    public void setRoleDAO(IRoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

    public StudentDTO getStudentDTO() {
        return studentDTO;
    }

    public void setStudentDTO(StudentDTO studentDTO) {
        this.studentDTO = studentDTO;
    }
}
